import axios from 'axios'
import {refresh} from "@/api/api";


axios.defaults.baseURL = '/';
axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/json';


// 创建axios实例
axios.create({
  baseURL: '/', // api的base_url
  timeout: 10000, // 请求超时时间
});

// 请求拦截器
axios.interceptors.request.use(config => {
    const access_token = localStorage.getItem('access_token')
    access_token && (config.headers.Authorization = `Bearer ${access_token}`);
    return config;
  },
  error => {
    return Promise.error(error);
  })

// 响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const {code} = response.data
      if (code === 401) refresh(localStorage.getItem('refresh_token')).then(res => {
        const {access_token} = res.data.data
        access_token && localStorage.setItem('access_token', access_token)
      })
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    if (error.response.status) {

      return Promise.reject(error.response);
    }
  })

export default axios;